import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/403', '/hkkeywspulgin']
const isUM = window.loginType == 'UM'

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  // 在免登录白名单，直接进入；否则需要验证token是否存在
  if (whiteList.indexOf(to.path) > -1) {
    next()
    return
  }

  if (!getToken() && !isUM) {
    next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    next()
    NProgress.done()
    return
  }

  /* has token*/
  if (store.getters.roles.length === 0) {
    // 判断当前用户是否已拉取完user_info信息
    store
      .dispatch('GetInfo')
      .then(() => {
        store.dispatch('GenerateRoutes').then((accessRoutes) => {
          // 根据roles权限生成可访问的路由表
          router.addRoutes(accessRoutes) // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        })
      })
      .catch((err) => {
        isRelogin.show = false
        if (err.redirect) {
          location.href = err.redirect
        }
        redirect(next)
      })
  } else {
    redirect(next)
  }
})

router.afterEach(() => {
  NProgress.done()
})

/**
 * 移除URL上code和state的参数,并重定向到新地址
 */
function redirect(next) {
  let url = location.href
  if ((url.indexOf('code=') == -1) & (url.indexOf('state=') == -1)) {
    next()
    return
  }

  const reg = new RegExp('&?code=[^&]*|state=[^&]*|sid=[^&]*', 'gi')
  url = url.replace(reg, '')
  if (url.indexOf('?&') != -1) {
    url = url.replace('?&', '?')
  }
  if (url.endsWith('&')) {
    url = url.substring(0, url.length - 1)
  }
  if (url.endsWith('?')) {
    url = url.substring(0, url.length - 1)
  }

  location.href = url

  next()
}
